/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * TCPTester.java
 *
 * Created on Jul 11, 2009, 10:33:10 AM
 */
package org.dbdir.test;

import java.awt.event.KeyEvent;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;
import org.dbdir.core.Logger;
import org.dbdir.core.xml.XMLParser;
import org.w3c.dom.NodeList;

/**
 *
 * @author thotheolh
 */
public class TCPClientTester extends javax.swing.JFrame {

    Socket sock = null;
    PrintWriter out = null;
    BufferedReader in = null;
    BufferedReader stdIn = null;
    XMLParser parser = new XMLParser();
    private Logger logger;

    /** Creates new form TCPTester */
    public TCPClientTester(Logger logger) {
        initComponents();
        this.logger = logger;
        this.setSize(516, 300);
        this.rawAppend("Type 'dbdir' to start followed by 'login usr=<username> pwd=<password>' to continue...\n\r");
        commandTf.grabFocus();
    }

    public void initConn() {
        try {
            try {
                sock = new Socket(getIPAddrFromConf(), 10999);
                out = new PrintWriter(sock.getOutputStream(), true);
                in = new BufferedReader(new InputStreamReader(sock.getInputStream()));
            } catch (UnknownHostException ex) {
                logger.log(2, ex.getMessage());
            } catch (IOException ex) {
                logger.log(2, ex.getMessage());
            }
            stdIn = new BufferedReader(new InputStreamReader(System.in));
            String fromServer;
            String fromUser;
            while ((fromServer = in.readLine()) != null) {
                System.out.println("Server: " + fromServer);
                this.appendText(fromServer);
                checkConditions(fromServer);
            }
        } catch (IOException ex) {
            logger.log(2, ex.getMessage());
        }
    }

    private void checkConditions(String fromServer) {
        if (fromServer.equals("ended")) {
            parseCommand("exit");
        }
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jScrollPane1 = new javax.swing.JScrollPane();
        jTextArea1 = new javax.swing.JTextArea();
        commandPane = new javax.swing.JPanel();
        commandTf = new javax.swing.JTextField();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        jTextArea1.setBackground(javax.swing.UIManager.getDefaults().getColor("Panel.background"));
        jTextArea1.setColumns(20);
        jTextArea1.setEditable(false);
        jTextArea1.setFont(new java.awt.Font("Tahoma", 1, 13));
        jTextArea1.setRows(5);
        jScrollPane1.setViewportView(jTextArea1);

        getContentPane().add(jScrollPane1, java.awt.BorderLayout.CENTER);

        commandPane.setBorder(javax.swing.BorderFactory.createTitledBorder("Command: "));
        commandPane.setLayout(new java.awt.BorderLayout());

        commandTf.setFont(new java.awt.Font("Courier New", 0, 14));
        commandTf.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                commandTfActionPerformed(evt);
            }
        });
        commandTf.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                commandTfKeyPressed(evt);
            }
        });
        commandPane.add(commandTf, java.awt.BorderLayout.CENTER);

        getContentPane().add(commandPane, java.awt.BorderLayout.SOUTH);

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void commandTfActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_commandTfActionPerformed
        // TODO add your handling code here:
}//GEN-LAST:event_commandTfActionPerformed

    private void commandTfKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_commandTfKeyPressed
        // TODO add your handling code here:
        if (evt.getKeyCode() == KeyEvent.VK_ENTER) {
            parseCommand(commandTf.getText());
            commandTf.setText("");
        }
}//GEN-LAST:event_commandTfKeyPressed

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                new TCPClientTester(new Logger()).setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JPanel commandPane;
    private javax.swing.JTextField commandTf;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTextArea jTextArea1;
    // End of variables declaration//GEN-END:variables

    private void parseCommand(String text) {
        if (text.equalsIgnoreCase("quit") || text.equalsIgnoreCase("bye") || text.equalsIgnoreCase("exit")) {
            try {
                out.close();
                in.close();
                stdIn.close();
            } catch (IOException ex) {
                logger.log(2, ex.getMessage());
                System.exit(1);
            }
            System.exit(0);
        } else if (text.equalsIgnoreCase("clear")) {
            this.clearConsole();
        } else if (text.equalsIgnoreCase("autotest")) {
            this.runAutoTest();
        } else {
            out.println(text);
            this.commandAppend(text);
        }
    }

    public void appendText(String text) {
        jTextArea1.append("Server> " + text + "\n");
    }

    public void rawAppend(String text) {
        jTextArea1.append(text + "\n");
    }

    public void commandAppend(String text) {
        jTextArea1.append(">: " + text + "\n");
    }

    public void clearConsole() {
        jTextArea1.setText("");
    }

    private String getIPAddrFromConf() {
        XMLParser xml = new XMLParser();
        NodeList nodes = xml.doParse("client.xml", "ipaddr");
        return nodes.item(0).getTextContent();
    }

    private void runAutoTest() {
        /*Look up for 'autotext.xml' script in 'script/autotest' directory in the client side and use an xml parser to valid and gather <case> elements*/
        NodeList nodes;
        File script = new File("script/autotest/autotest.xml");


        if (script.exists()) {
            nodes = parser.doParse(script.getAbsolutePath());


            for (int i = 0; i
                    < nodes.getLength(); i++) {
                if (nodes.item(i).getNodeName().equals("case")) {
                    this.parseCommand(nodes.item(i).getTextContent());


                }
            }
        } else {
            this.rawAppend("autotest scripts does not exist !");

        }
    }
}
